package com.zoro.dyformservice.support.filter.auth.url;


import com.zoro.dyformservice.utils.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author zhaoxingwu
 */
public class AuthTypeBo {

    private final Set<String> equalCheckUriList = new HashSet<>();
    private final Set<String> startWithCheckUriList = new HashSet<>();
    private final Set<Pattern> patternCheckUriList = new HashSet<>();

    public AuthTypeBo(List<AuthUrlSetting> authUrlSettings) {
        this.groupData(authUrlSettings);
    }

    public void groupData(List<AuthUrlSetting> settings) {
        if (CollectionUtils.isEmpty(settings)) {
            return;
        }
        settings.forEach(v -> {
            switch (v.getMatchType()) {
                case EQUAL -> equalCheckUriList.add(v.getUri());
                case START_WITH -> startWithCheckUriList.add(v.getUri());
                case PATTERN -> patternCheckUriList.add(Pattern.compile(v.getUri()));
            }
        });
    }

    public boolean isCheck(String uri) {
        if (this.equalCheckUriList.contains(uri)) {
            return true;
        }
        for (String u : this.startWithCheckUriList) {
            if (u != null && u.startsWith(uri)) {
                return true;
            }
        }
        for (Pattern p : patternCheckUriList) {
            if (p.matcher(uri).find()) {
                return true;
            }
        }
        return false;
    }
}
